package com.boco.config;

import com.boco.common.util.Utils;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * Created by pandengke/pdkkpdk@163.com on 2017/11/22.
 */
@Component
public class ApplicationEventListener implements ApplicationListener, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final String template = "============= http://%s:%s%s/swagger-ui.html =============";

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        String port = applicationContext.getEnvironment().getProperty("server.port", "8080");
        String contextPath = applicationContext.getEnvironment().getProperty("server.context-path", "");
        if (event instanceof ApplicationReadyEvent) {
            if (port != null) {
                printlnHomeUrl(template, port, contextPath);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private void printlnHomeUrl(String template, String port, String contextPath) {
        Utils.netaddress().forEach(address ->{
            System.out.println(String.format(template, address, port, contextPath));
        });
    }


}